有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何计算用户从5个组合框中选择的项目的总成本

我已经完成了600行代码,制作了五个组合框。我可以显示每个项目的价格,但无法显示所选项目的总数。这里是我所做的其中一个组合框的代码

    lights.setConverter(new StringConverter<Light>() {
        @Override
        public String toString(Light object) {
            return object.getName();
        }

        @Override
        public Light fromString(String string) {
            return null;
        }
    });



    lights.setItems(FXCollections.observableArrayList
           (new Light ("Incandescent", 5.23),
            new Light ("Halogen", 5.75),
            new Light ("fluorescent",7.29),
            new Light ("Compact fluorescent bulbs",4.83),
            new Light ("LED",4.83)));


    lights.setPromptText("Please select a light");
    lights.setPrefWidth(100);


         lights.valueProperty().addListener((obs, oldVal, newVal) -> {
         String selectionText = "The price for the " + newVal.getName() + " light is : $" + newVal.getPrice();
       lightNamePrice.setText(selectionText);
    });

 private class Light {
    private String name;
    private Double price;

    private Double getPrice() {
        return price;
    }

    private String getName() {
        return name;
    }

    private Light(String name, Double price) {
        this.name = name;
        this.price = price;

    }

}

我这样做对吗? 我该怎么做才能找到用户选择的其他4个组合框的总成本


共 (1) 个答案

  1. # 1 楼答案

    使用绑定:

    DoubleBinding total = Bindings.createDoubleBinding(() -> {
        double total = 0 ;
        if (lights.getValue() != null) total += lights.getValue().getPrice();
        // similarly for other combo boxes...
        return total ;
    }, lights.valueProperty(), otherComboBox.valueProperty() /* etc for other combos*/);
    

    然后你可以做类似的事情

    totalPriceLabel.textProperty().bind(total.asString());